<template>
  <div class="overflow-hidden flex-1">
    <div class="flex justify-between items-center">
      <BaseTitle title="优惠" class="w-[100px] items-center" />
      <div class="flex items-center justify-end min-w-[250px] mr-2">
        <a-button size="small" type="text" class="ml-2" @click="expand = !expand">
          <UpOutlined v-if="expand" />
          <DownOutlined v-else />
        </a-button>
        <span>优惠：</span>
        <span class="text-red-500 font-bold">￥{{ formatAmount(discountAmount) }}</span>
      </div>
    </div>
    <a-tabs v-show="expand" v-model:active-key="activeTab" class="flex overflow-x-auto overflow-y-hidden flex-1">
      <a-tab-pane :key="0" class="h-full">
        <template #tab>
          {{ selectedCouponAmount ? `抵用券(￥${formatAmount(selectedCouponAmount)})` : '抵用券' }}
        </template>
        <a-list v-if="ticketList.length > 0" size="small" :data-source="ticketList" :grid="{ column: 2 }" class="h-[200px] overflow-auto min-w-[750px]">
          <template #renderItem="{ item }">
            <a-list-item :class="item.status === 2 ? 'cursor-not-allowed' : 'cursor-pointer'" @click="onClickTicket(item)">
              <div class="shadow-sm hover:shadow-md rounded overflow-hidden border" :class="{ 'border-[#d2a96f]': item.id === activeTicket }">
                <CheckCircleFilled v-if="item.id === activeTicket" class="text-white absolute top-2 right-6 text-lg" />
                <div class="flex items-center pt-1 pb-2" :class="getClass(item)">
                  <div class="ml-3">
                    <span>￥</span>
                    <span class="font-bold text-2xl">{{ item.offsetAmount }}</span>
                    <div class="pl-2 text-xs">抵用券</div>
                  </div>
                  <a-divider type="vertical" class="h-10 mx-4" />
                  <div>
                    <div>{{ item.couponsName }}</div>
                    <div>{{ item.status === 2 ? '有效期已过' : '有效期至 ' + item.endDate }}</div>
                  </div>
                </div>
                <div class="p-2">使用条件：{{ item.conditons }}</div>
              </div>
            </a-list-item>
          </template>
        </a-list>
        <a-empty v-else description="暂无抵用券" />
      </a-tab-pane>
      <a-tab-pane :key="1" class="h-full">
        <template #tab>
          <a-badge :dot="showMemberCardBadge">
            {{ vipCardInfo.memberInput ? `会员卡(￥${formatAmount(vipCardInfo.memberInput)})` : '会员卡' }}
          </a-badge>
        </template>
        <div v-if="Object.keys(vipCardInfo).length > 0" class="flex flex-wrap">
          <div class="member-box border rounded-xl p-2 shadow-sm overflow-hidden">
            <div class="border border-white rounded-xl px-4 py-2 relative" style="border-color: #eacc8b">
              <img src="@/assets/images/Frame.png" alt="" srcset="" class="w-[120px] h-[80px] absolute right-0 top-0" />
              <div class="text-color flex items-center">
                <img class="w-[59px] h-[28px]" src="@/assets/images/vip-img.png" alt="" />
                <div class="ml-2 mt-2">{{ vipCardInfo?.gradename }}</div>
              </div>
              <div class="text-color text-xs mt-2">有效期至{{ formatDate(vipCardInfo?.validatedate) }}</div>
              <div class="mt-2">
                <div class="text-color text-xs">余额(元)</div>
                <div class="flex justify-between items-center mb-1 mt-2">
                  <div class="text-xl text-color flex items-end">
                    {{ formatAmount(vipCardInfo?.zje) }}
                    <a-popover placement="topLeft">
                      <template #content>
                        <div class="p-3">
                          <div>充值金额 ￥{{ vipCardInfo?.balance }}</div>
                          <div>赠送金额 ￥{{ vipCardInfo?.givebalance }}</div>
                        </div>
                      </template>
                      <QuestionCircleOutlined class="text-xs pb-1.5 pl-1" />
                    </a-popover>
                  </div>
                  <div class="flex items-center relative">
                    <a-input v-model:value="vipCardInfo.memberInput" v-input:float.2 placeholder="本次使用金额" @blur="onBlurMember" />
                    <a-button type="link" class="!text-white !text-xs" size="small" @click="onClickAllPrice">全部</a-button>
                    <div v-if="Number(vipCardInfo.memberInput) > vipCardInfo.zje" class="text-rose-500 !text-xs absolute -bottom-3 right-15">
                      *不可大于当前余额
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <a-empty v-else description="暂无会员卡" />
      </a-tab-pane>
      <a-tab-pane :key="2">
        <template #tab>
          {{ directDiscountAmount ? `直接优惠(￥${formatAmount(directDiscountAmount)})` : '直接优惠' }}
        </template>
        <div class="flex h-[134px] pt-2">
          <a-input-number v-model:value="directDiscountInput" disabled placeholder="请输入" class="w-60 h-8" />
          <a-button type="primary" class="ml-2" disabled @click="onClickDirectDiscount">确定</a-button>
        </div>
      </a-tab-pane>
      <template v-if="activeTab === 0" #rightExtra>
        <div class="flex">
          <div class="mr-2 w-[50px] leading-8">卡券</div>
          <a-input v-model:value="couponInput" :disabled="!brId" placeholder="请扫描券码快速定位" @keydown.enter="onBlur" @blur="onBlur" />
        </div>
      </template>
    </a-tabs>
    <!-- <div class="flex items-center justify-end mt-2">
        <span>优惠：</span>
        <span class="text-red-500 font-bold">￥{{ formatAmount(discountAmount) }}</span>
      </div> -->
  </div>
</template>
<script setup>
import { ref, watch } from 'vue'
import { CheckCircleFilled, QuestionCircleOutlined, DownOutlined, UpOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { formatAmount, formatDate } from '@/utils/format'
import { post } from '@/utils/request'

const emit = defineEmits(['success'])
const props = defineProps({
  brId: {
    type: String,
    default: null
  },
  medicalPrice: {
    type: [String, Number],
    default: 0
  },
  isOptometry: {
    type: Boolean,
    default: false
  },
  isShowTabs: {
    type: Boolean,
    default: false
  }
})
const activeTab = ref(0) //当前tab
const activeTicket = ref() //选择的优惠券
const selectedCouponAmount = ref(0) // 选中的抵用券的金额
const expand = ref(false)
const discountAmount = ref(0)
const directDiscountAmount = ref('') //直接优惠
const couponInput = ref('') // 优惠卷检索框
const ticketList = ref([])
const vipCardInfo = ref({})
const getClass = (item) => {
  if (item.status === 2) {
    return 'bg-thin text-[#b7b7b7]'
  } else {
    return {
      'bg-[#d2a96f] text-white': item.id === activeTicket.value,
      'bg-[#fcf2e3] text-[#d2a96f]': item.id !== activeTicket.value
    }
  }
}

// 检索优惠卷
const onBlur = () => {
  // couponInput.value &&
  getPatientCouponList()
}

// 优惠卷
const getPatientCouponList = async () => {
  discountAmount.value = 0
  activeTicket.value = ''
  const { code, data, msg } = await post('/outp/oupCharge/getPatientCouponList', {
    brId: props.brId,
    status: '0',
    pyjm: couponInput.value
  })
  if (code !== 0) return message.error(msg)
  ticketList.value = data
  if (data.length) {
    expand.value = true
  }
}
// 选中优惠卷
const onClickTicket = (row) => {
  if (row.status === 2) return
  if (activeTicket.value === row.id) {
    emit('success', '', '', '优惠券')
    activeTicket.value = ''
    discountAmount.value = ''
    selectedCouponAmount.value = ''
  } else {
    if (row.offsetAmount <= props.medicalPrice) {
      activeTicket.value = row.id
      emit('success', row.id, row.offsetAmount, '优惠券')
      selectedCouponAmount.value = row.offsetAmount
      discountAmount.value = Number(selectedCouponAmount.value || 0) + Number(vipCardInfo.value.memberInput || 0) + Number(directDiscountAmount.value || 0)
    } else {
      message.warning('优惠金额不可超过实付金额')
    }
  }
}
const showMemberCardBadge = ref(false)
// 会员卡
const getMemberCardList = async () => {
  showMemberCardBadge.value = false
  discountAmount.value = 0
  const { code, data, msg } = await post('/outp/oupCharge/getMemberCard', {
    brId: props.brId
  })
  if (code !== 0) return message.error(msg)
  if (data) {
    vipCardInfo.value = data
    vipCardInfo.value.memberInput = null
    if (vipCardInfo.value.zje) {
      expand.value = true
      showMemberCardBadge.value = true
    }
  }
}
const btnLoading = ref(false)
// 会员卡点全部
const onClickAllPrice = async () => {
  if (btnLoading.value) return
  if (!props.medicalPrice) return message.warning('实付金额为0')
  if (vipCardInfo.value.memberInput) {
    btnLoading.value = true
    vipCardInfo.value.memberInput = null
    emit('success', '', 0, '会员卡')
    await new Promise((resolve) => setTimeout(resolve, 800))
    btnLoading.value = false
  }

  //总金额大于应付金额
  if (vipCardInfo.value.zje > Number(props.medicalPrice)) {
    vipCardInfo.value.memberInput = Number(props.medicalPrice)
  } else {
    vipCardInfo.value.memberInput = Number(vipCardInfo.value.zje)
  }
  discountAmount.value = Number(selectedCouponAmount.value || 0) + Number(vipCardInfo.value.memberInput || 0) + Number(directDiscountAmount.value || 0)
  vipCardInfo.value.memberInput && emit('success', vipCardInfo.value.cardno, vipCardInfo.value.memberInput, '会员卡')
}
// 会员卡失去焦点
const onBlurMember = async () => {
  if (vipCardInfo.value.memberInput) {
    emit('success', '', 0, '会员卡')
    await new Promise((resolve) => setTimeout(resolve, 800))
  }
  if (Number(vipCardInfo.value.memberInput || 0) > props.medicalPrice) {
    vipCardInfo.value.memberInput = ''
    return message.error('优惠金额不能超过实付金额')
  }
  if (vipCardInfo.value.memberInput > vipCardInfo.value.zje) {
    vipCardInfo.value.memberInput = vipCardInfo.value.zje
  } else {
    discountAmount.value = Number(selectedCouponAmount.value || 0) + Number(vipCardInfo.value.memberInput || 0) + Number(directDiscountAmount.value || 0)
  }
  emit('success', vipCardInfo.value.cardno, vipCardInfo.value.memberInput, '会员卡')
}

// 计算优惠金额
// const getPreferentialPrice = () => {
//   // 选中了优惠卷，并且小于实收金额
//   if (selectedCouponAmount.value && selectedCouponAmount.value < props.medicalPrice) {
//     // 给会员卡输入框赋值实收金额
//     vipCardInfo.value.memberInput = Number(props.medicalPrice)
//     // 优惠金额=会员卡输入框的金额+选中的优惠卷的金额
//     discountAmount.value = Number(vipCardInfo.value.memberInput) + Number(selectedCouponAmount.value)
//   } else {
//     if (selectedCouponAmount.value && selectedCouponAmount.value > props.medicalPrice) {
//       discountAmount.value = +selectedCouponAmount.value
//       vipCardInfo.value.memberInput = 0
//     } else {
//       // 如果会员卡总金额大于实收金额，那就把实收金额赋值给会员卡的输入框就是全部优惠
//       // 如果不大于实收金额，那就把会员卡的全部金额赋值给输入框
//       if (vipCardInfo.value.zje > Number(props.medicalPrice)) {
//         vipCardInfo.value.memberInput = Number(props.medicalPrice)
//         discountAmount.value = +vipCardInfo.value.memberInput
//       } else {
//         vipCardInfo.value.memberInput = vipCardInfo.value.zje
//         discountAmount.value = +vipCardInfo.value.zje
//       }
//       vipCardInfo.value[0].memberInput = props.medicalPrice
//       discountAmount.value = props.medicalPrice
//     }
//   }
//   vipCardInfo.value.memberInput && emit('success', vipCardInfo.value.cardno, vipCardInfo.value.memberInput, 2)
//   !vipCardInfo.value.memberInput && emit('success', '', '', 2)
// }
const directDiscountInput = ref('')
const onClickDirectDiscount = () => {
  directDiscountAmount.value = directDiscountInput.value
  discountAmount.value = Number(selectedCouponAmount.value || 0) + Number(vipCardInfo.value.memberInput || 0) + Number(directDiscountAmount.value || 0)
  emit('success', '', directDiscountAmount.value, '直接优惠')
}
watch(
  () => props.brId,
  async (val) => {
    if (val) {
      getPatientCouponList()
      getMemberCardList()
      // Object.keys(vipCardInfo.value).length > 0 && getPreferentialPrice()
    } else {
      ticketList.value = []
      vipCardInfo.value = {}
      discountAmount.value = 0
      directDiscountInput.value = ''
      couponInput.value = ''
    }
  },
  {
    immediate: true
  }
)

// watch(
//   () => props.medicalPrice,
//   (val) => {
//     if (!val) {
//       ticketList.value = []
//       vipCardInfo.value = {}
//       discountAmount.value = 0
//       directDiscountAmount.value = 0
//       directDiscountInput.value = ''
//       couponInput.value = ''
//     } else {
//       // props.brId && Object.keys(vipCardInfo.value).length > 0 && getPreferentialPrice()
//     }
//   }
// )
</script>
<style lang="less" scoped>
.member-box {
  background: linear-gradient(to bottom, #fcecc4, #d5b676);
  // background-color: #fbeec8;
  .ant-input {
    width: 112px;
    height: 22px;
    margin: 0 12px;
    color: #8f6f3a;
    border: 0 !important;
  }
  .ant-input::placeholder {
    color: #baa787 !important;
    font-size: 12px;
  }
  .text-color {
    color: #8f6f3a;
    font-weight: 700;
  }
}
</style>
